package com.example.toutiao.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.toutiao.R;
import com.example.toutiao.db.CartItem;
import com.example.toutiao.db.DatabaseHelper;
import com.example.toutiao.db.Product;
import com.example.toutiao.ui.fragment.CheckoutDialogFragment;

import java.util.List;

//商品详情
public class ProductDetailActivity extends AppCompatActivity {

    private TextView tvDetailName, tvDetailPrice, tvDetailDescription;
    private ImageView imgDetail;
    private Button btnAddToCart, btnBuyNow;
    private ImageView btnGoToCart;

    private String name, description, image;
    private double price;
    private int id;

    @Override   @SuppressLint("MissingInflatedId")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);
     TextView tabBarTitle = findViewById(R.id.tabBarTitle);
        tabBarTitle.setText("商品详情");
        ImageView imgProduct = findViewById(R.id.imgDetail);
        tvDetailName = findViewById(R.id.tvDetailName);
        tvDetailPrice = findViewById(R.id.tvDetailPrice);
        tvDetailDescription = findViewById(R.id.tvDetailDescription);
        imgDetail = findViewById(R.id.imgDetail);
        btnAddToCart = findViewById(R.id.btnAddToCart);
        btnBuyNow = findViewById(R.id.btnBuyNow);
        btnGoToCart = findViewById(R.id.btnGoToCart);
        Intent intent = getIntent();
        name = intent.getStringExtra("name");
        description = intent.getStringExtra("description");
        price = intent.getDoubleExtra("price", 0.0);
        image = intent.getStringExtra("image");
        id = intent.getIntExtra("id",0);
        tvDetailName.setText(name);
        tvDetailPrice.setText("￥" + price);
        tvDetailDescription.setText(description);

        // 加入购物车按钮点击事件
        btnAddToCart.setOnClickListener(v -> {
            addToCart(id);
        });

        // 立即购买按钮点击事件
        btnBuyNow.setOnClickListener(v -> {
            SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
            String currentUsername = sharedPreferences.getString("username", "");

            if (currentUsername.isEmpty()) {
                Toast.makeText(ProductDetailActivity.this, "请先登录！", Toast.LENGTH_SHORT).show();
                return;
            }

            // 获取购物车商品列表
            DatabaseHelper dbHelper = new DatabaseHelper(this);
            List<CartItem> cartItems = dbHelper.getCartItemsByUsername(currentUsername);

            if (cartItems.isEmpty()) {
                Toast.makeText(ProductDetailActivity.this, "购物车为空，无法立即购买", Toast.LENGTH_SHORT).show();
                return;
            }

            // 计算总金额
            double totalAmount = 0;
            for (CartItem cartItem : cartItems) {
                totalAmount += cartItem.getProduct(dbHelper).getPrice() * cartItem.getQuantity();
            }

            // 创建订单，并将商品添加到订单表中
            for (CartItem cartItem : cartItems) {
                Product product = cartItem.getProduct(dbHelper);
                dbHelper.addOrder(currentUsername, product.getId(), cartItem.getQuantity());
            }

            dbHelper.clearCart(currentUsername);
            Toast.makeText(ProductDetailActivity.this, "购买成功！", Toast.LENGTH_SHORT).show();

            // 创建并显示结算确认对话框
            CheckoutDialogFragment checkoutDialogFragment = new CheckoutDialogFragment(cartItems, totalAmount);
            checkoutDialogFragment.show(getSupportFragmentManager(), "CheckoutDialog");
        });

        // 购物车按钮点击事件
        btnGoToCart.setOnClickListener(v -> {
            Intent cartIntent = new Intent(ProductDetailActivity.this, CartActivity.class);
            startActivity(cartIntent);
        });
    }

    // 将商品加入购物车的逻辑
    private void addToCart(int productId) {
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        String currentUsername = sharedPreferences.getString("username", "");

        if (currentUsername.isEmpty()) {
            Toast.makeText(ProductDetailActivity.this, "请先登录！", Toast.LENGTH_SHORT).show();
            return;
        }


        DatabaseHelper dbHelper = new DatabaseHelper(this);
        Product product = dbHelper.getProductById(productId);

        if (product == null) {
            Toast.makeText(ProductDetailActivity.this, "商品不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        boolean isExist = dbHelper.isProductInCart(currentUsername, productId);

        if (isExist) {
            dbHelper.updateCartQuantity(currentUsername, productId, 1);  // 增加一个商品
        } else {
            dbHelper.addToCart(currentUsername, productId, 1);
        }
        Toast.makeText(ProductDetailActivity.this, "商品已加入购物车！", Toast.LENGTH_SHORT).show();
    }
}
